package com.cindata

import com.cindata.dictionary.AccountNatureDict
import com.cindata.dictionary.BuildingTypeDict
import com.cindata.dictionary.DepositedStateDict
import com.cindata.dictionary.EstateStatusDict
import com.cindata.dictionary.EvaluateDict
import com.cindata.dictionary.ExecStatusDict
import com.cindata.dictionary.ForwardLoanStepDict
import com.cindata.dictionary.GuaranteeMethodDict
import com.cindata.dictionary.HouseTypeDict
import com.cindata.dictionary.LoanMethodDict
import com.cindata.dictionary.OrganizationNatureDict
import com.cindata.dictionary.RepaymentModeDict

class EstateImport
{

    EstateImportBatch batch

    String serialNumber
    // 贷款编号
    String externalId
    //外部ID 押品编号
    EstateStatusDict estateStatus
    //1： 在押  2： 到期
    String provinceName
    //  所在省
    String cityName
    //    城市名称*
    String districtName
    //    行政区名称
    String streetName
    //    街道名称
    City city
    //    城市*
    District district
    //    行政区
    Long streetId
    //    街道
    String address
    //    地址
    Integer buildYear
    //    建成年份
    BigDecimal buildArea
    //    面积*（平方米）
    BuildingTypeDict buildingType
    //   建筑类型（住宅、非住宅）,目前默认住宅
    Integer totalFloor
    //    总楼层
    Integer currentFloor
    //    当前层
    String contractNo
    //  贷款合同编号
    Date startDate
    //  放款日期
    BigDecimal loansEvaluateTotalPrice
    //  贷款评估总价
    BigDecimal loansEvaluatePrice
    //  贷款评估单价
    BigDecimal loansAmount
    //  贷款总金额
    BigDecimal ltv
    //  抵押率
    BigDecimal loansBalance
    //  贷款余额
    Date endDate
    // 最初贷款到期日期
    String mortgageeName
    //    抵押权人
    HouseTypeDict estateType
    //    房屋类型
    String accountName
    //    受理网点名称
    Boolean isFirstHouse
    //    是否首套房
    BigDecimal downPaymentAmount
    //    首付金额
    BigDecimal publicFundLoansAmount
    //    公积金贷款金额
    BigDecimal bankLoansAmount
    //    商业贷款金额（元）
    String loansBankName
    //    放款银行名称（大行名）
    Integer loansDuration
    //    最初应还款期数（月）
    RepaymentModeDict starRepaymentMode
    //    最初还款方式
    Integer repaymentDate
    //    每月应还款日
    ForwardLoanStepDict forwardLoanStep
    //    提前放款步骤
    LoanMethodDict loanMethod
    //    放款方式
    RepaymentModeDict curRepaymentMode
    //    当前还款方式
    BigDecimal curRecycleTotalCapital
    //    当前回收总本金（元）
    BigDecimal curRecycleTotalInterest
    //    当前回收总利息（不含罚息）（元）
    BigDecimal curRecycleTotalFine
    //    当前回收总罚息（元）
    Integer curHasPaymentTODuration
    //    当前已还款期数(含转逾期)（月）
    Integer curHasPaymentDuration
    //    当前已还款期数(不含转逾期)（月）
    Integer remainTime
    //    当前剩余还款期数（月）
    GuaranteeMethodDict guaranteeMethod
    //    担保方式
    Account guaranteeInstitution
    //    担保机构
    String borrPublicFundAccount
    //    主借款人公积金账号
    String borrName
    //    主借款人姓名
    String borrPhone
    //    主借款人联系电话
    String borrIdCardNo
    //    主借款人身份证号
    Date borrBirthday
    //    主借款人出身年月日
    AccountNatureDict borrAccountNature
    //    主借款人户口性质
    Integer borrOwnHouseCount
    //    主借款人家庭已购房套数
    String borrWorkUnitName
    //    主借款人工作单位名称
    OrganizationNatureDict borrWorkUnitNature
    //    主借款人工作单位性质
    DepositedStateDict borrDepositedState
    //    主借款人当前缴存状态
    BigDecimal borrDepositBaseOnLoans
    //    主借款人贷款时月缴存基数（元）
    BigDecimal borrDepositAmountOnLoans
    //    主借款人贷款时月缴存额（元）
    BigDecimal borrDepositBaseOnCurrent
    //    主借款人当前月缴存基数（元）
    BigDecimal borrDepositAmountOnCurrent
    //    主借款人当前月缴存额（元）
    BigDecimal borrFmiOnLoans
    //    主借款人贷款时家庭月收入（元）

    Date evaluateDate
    // 评估日期

    EvaluateDict evaluateType
    // 1:自动评估 2：人工评估

    ExecStatusDict evaluateStatue

    String addressSplitResult
    // 保存拆分的结果

    BigDecimal unitPrice
    BigDecimal totalPrice

    Long communityId
    //    小区ID
    String communityName
    String communityAddress
    Long buildingId
    //    楼栋ID
    String buildingName
    Long unitId
    //    单元ID
    String unitName
    Long houseId
    //    户ID
    String houseName
    Double x
    // 经度
    Double y
    // 纬度
    String failReason
    // 评估失败原因

    String evaluateCode

    Account latestEvaluateAccount
    // 最新评估机构

    Date latestEvaluateDate

    Date createdDate = new Date()
    Date modifiedDate = new Date()
    User createBy
    User modifyBy

    Integer totalBuildingNum
    Integer totalHouseNum

    EstateImport()
    {
    }

    EstateImport(String provinceName, EstateImportBatch batch, String externalId, String cityName, String address, Date createdDate, User createBy)
    {
        this.provinceName = provinceName
        this.batch = batch
        this.externalId = externalId
        this.cityName = cityName
        this.address = address
        this.createdDate = createdDate
        this.createBy = createBy
    }

    static constraints = {

        serialNumber nullable: true, blank: true

        batch nullable: true, blank: true
        provinceName maxSize: 100, nullable: true, blank: true
        cityName maxSize: 100, nullable: true, blank: true
        districtName maxSize: 100, nullable: true, blank: true
        streetName maxSize: 100, nullable: true, blank: true, comment: '街道名称'
        city nullable: true, blank: true, comment: '城市'
        district nullable: true, blank: true, comment: '行政区'
        streetId nullable: true, blank: true, comment: '街道'
        address maxSize: 255, nullable: true, blank: true
        buildYear maxSize: 4, nullable: true, blank: true, comment: '建筑年份'
        buildArea precision: 7, scale: 2, nullable: true, blank: true
        buildingType nullable: true, blank: true, comment: '建筑类型(住宅、非住宅)'
        totalFloor maxSize: 10, nullable: true, blank: true
        currentFloor maxSize: 10, nullable: true, blank: true
        externalId maxSize: 128, nullable: true, blank: true
        contractNo maxSize: 64, nullable: true, blank: true
        loansEvaluateTotalPrice precision: 15, scale: 2
        loansEvaluatePrice precision: 15, scale: 2
        loansAmount precision: 15, scale: 2
        loansDuration maxSize: 10
        loansBalance precision: 15, scale: 2

        startDate nullable: true, blank: true
        endDate nullable: true, blank: true

        createdDate nullable: true, blank: true
        modifiedDate nullable: true, blank: true
        createBy nullable: true, blank: true
        modifyBy nullable: true, blank: true
        remainTime nullable: true, blank: true
        addressSplitResult nullable: true, blank: true

        ltv precision: 5, scale: 4, nullable: true, blank: true
        estateStatus nullable: true, blank: true
        evaluateType nullable: true, blank: true
        evaluateStatue nullable: true, blank: true
        evaluateDate nullable: true, blank: true
        evaluateCode nullable: true, blank: true, maxSize: 30

        unitPrice precision: 15, scale: 2, nullable: true, blank: true
        totalPrice precision: 15, scale: 2, nullable: true, blank: true

        communityName maxSize: 128, nullable: true, blank: true
        communityId nullable: true, blank: true
        communityAddress maxSize: 128, nullable: true, blank: true, comment: '小区地址'
        buildingName maxSize: 128, nullable: true, blank: true
        buildingId nullable: true, blank: true
        unitName maxSize: 128, nullable: true, blank: true
        unitId nullable: true, blank: true
        houseName maxSize: 128, nullable: true, blank: true
        houseId nullable: true, blank: true

        x nullable: true, blank: true
        y nullable: true, blank: true
        failReason maxSize: 255, nullable: true, blank: true, comment: '评估失败原因'

        mortgageeName maxSize: 100, nullable: true, blank: true, comment: '抵押权人'
        estateType nullable: true, blank: true, comment: '房屋类型'
        accountName maxSize: 100, nullable: true, blank: true, comment: '受理网点名称'
        isFirstHouse nullable: true, blank: true, default: true, comment: '是否首套房'
        downPaymentAmount nullable: true, blank: true, precision: 15, scale: 2, comment: '首付金额'
        publicFundLoansAmount nullable: true, blank: true, precision: 15, scale: 2, comment: '公积金贷款金额'
        bankLoansAmount nullable: true, blank: true, precision: 15, scale: 2, comment: '商业贷款金额（元）'
        loansBankName maxSize: 100, nullable: true, blank: true, comment: '放款银行名称（大行名）'
        starRepaymentMode nullable: true, blank: true, comment: '最初还款方式'
        repaymentDate maxSize: 2, nullable: true, blank: true, comment: '每月还款日'
        forwardLoanStep nullable: true, blank: true, comment: '提前放款步骤'
        loanMethod nullable: true, blank: true, comment: '放款方式'
        curRepaymentMode nullable: true, blank: true, comment: '当前还款方式'
        curRecycleTotalCapital nullable: true, blank: true, precision: 15, scale: 2, comment: '当前回收总本金（元）'
        curRecycleTotalInterest nullable: true, blank: true, precision: 15, scale: 2, comment: '当前回收总利息（不含罚息）（元）'
        curRecycleTotalFine nullable: true, blank: true, precision: 15, scale: 2, comment: '当前回收总罚息（元）'
        curHasPaymentTODuration maxSize: 4, nullable: true, blank: true, comment: '当前已还款期数(含转逾期)（月）'
        curHasPaymentDuration maxSize: 4, nullable: true, blank: true, comment: '当前已还款期数(不含转逾期)（月）'
        guaranteeMethod nullable: true, blank: true, comment: '担保方式'
        guaranteeInstitution maxSize: 100, nullable: true, blank: true, comment: '担保机构'
        borrPublicFundAccount maxSize: 50, nullable: true, blank: true, comment: '主借款人公积金账号'
        borrName maxSize: 50, nullable: true, blank: true, comment: '主借款人姓名'
        borrPhone maxSize: 20, nullable: true, blank: true, comment: '主借款人联系电话'
        borrIdCardNo maxSize: 20, nullable: true, blank: true, comment: '主借款人身份证号'
        borrBirthday nullable: true, blank: true, comment: '主借款人出身年月日'
        borrAccountNature nullable: true, blank: true, comment: '主借款人户口性质'
        borrOwnHouseCount maxSize: 8, nullable: true, blank: true, comment: '主借款人家庭已购房套数'
        borrWorkUnitName maxSize: 100, nullable: true, blank: true, comment: '主借款人工作单位名称'
        borrWorkUnitNature nullable: true, blank: true, comment: '主借款人工作单位性质'
        borrDepositedState nullable: true, blank: true, comment: '主借款人当前缴存状态'
        borrDepositBaseOnLoans nullable: true, blank: true, precision: 15, scale: 2, comment: '主借款人贷款时月缴存基数（元）'
        borrDepositAmountOnLoans nullable: true, blank: true, precision: 15, scale: 2, comment: '主借款人贷款时月缴存额（元）'
        borrDepositBaseOnCurrent nullable: true, blank: true, precision: 15, scale: 2, comment: '主借款人当前月缴存基数（元）'
        borrDepositAmountOnCurrent nullable: true, blank: true, precision: 15, scale: 2, comment: '主借款人当前月缴存额（元）'
        borrFmiOnLoans nullable: true, blank: true, precision: 15, scale: 2, comment: '主借款人贷款时家庭月收入（元）'

        totalBuildingNum nullable: true, blank: true, comment: '总楼栋数'
        totalHouseNum nullable: true, blank: true, comment: '总户数'

        latestEvaluateAccount nullable: true, blank: true, comment: '总户数'
        latestEvaluateDate nullable: true, blank: true

    }

    def afterInsert()
    {
        // def mortgage = Mortgage.CreateFromEstateImport(this)
    }

    def afterUpdate()
    {
        this.updateMatchNum()
    }

    // 评估成功，进入押品表
    def evaluteSuccess()
    {
        def estate = Estate.findByExternalId(externalId)
        if (!estate)
        {
            estate = new Estate()
        }
        estate.batch = this.batch
        estate.latestEvaluateAccount = this.latestEvaluateAccount
        estate.externalId = this.externalId
        City city = City.findByName(this.cityName)
        estate.city = city
        estate.province = city?.parentArea
        District district = District.findByNameAndParentArea(this.districtName, city)
        // 通过区域名称和所属城市定位区域ID
        estate.district = district
        estate.estateStatus = this.estateStatus

        estate.communityId = this.communityId
        estate.communityName = this.communityName
        estate.buildingId = this.buildingId
        estate.buildingName = this.buildingName
        estate.unitId = this.unitId
        estate.unitName = this.unitName
        estate.houseId = this.houseId
        estate.houseName = this.houseName
        estate.streetId = this.streetId
        estate.streetName = this.streetName

        estate.buildYear = this.buildYear
        estate.buildArea = this.buildArea
        estate.buildingType = this.buildingType

        estate.unitPrice = this.unitPrice
        estate.totalPrice = this.totalPrice
        estate.ltv = this.ltv
        if (this.loansBalance && this.totalPrice)
        {
            estate.cltv = (this.loansBalance / this.totalPrice)
        }
        estate.sourceAddress = this.address
        estate.sourceBuildArea = this.buildArea
        estate.sourceTotalFloor = this.totalFloor
        estate.sourceCurrentFloor = this.currentFloor

        estate.loansEvaluateTotalPrice = this.loansEvaluateTotalPrice
        estate.loansEvaluatePrice = this.loansEvaluatePrice
        estate.loansAmount = this.loansAmount
        estate.loansBalance = this.loansBalance

        estate.startDate = this.startDate
        estate.endDate = this.endDate
        estate.matchDate = new Date()
        estate.valuationDate = this.evaluateDate

        estate.x = this.x
        estate.y = this.y
        estate.loansDuration = this.loansDuration
        estate.remainTime = this.remainTime
        estate.account = this.createBy.account
        estate.isEstate = true

        estate.totalBuildingNum = this.totalBuildingNum
        estate.totalHouseNum = this.totalHouseNum
        estate.modifiedDate = new Date()
        estate.latestEvaluateDate = this.latestEvaluateDate
        estate.latestEvaluatePrice = this.totalPrice

        estate.save()

        ValuationHistory valuationHistory = new ValuationHistory()
        valuationHistory.evaluateCode = this.evaluateCode
        valuationHistory.name = this.communityName
        valuationHistory.valuationDate = this.latestEvaluateDate
        valuationHistory.unitPrice = this.unitPrice
        valuationHistory.totalPrice = this.totalPrice
        valuationHistory.sourceId = estate?.id
        valuationHistory.sourceClass = "estate"
        valuationHistory.evaluateStatus = ExecStatusDict.SUCCESS()
        valuationHistory.evaluateType = this.evaluateType
        valuationHistory.save(flush: true)

        def userCost = UserCost.findBySourceIdAndSourceClass(this.id, this.class.toString())
        if (userCost)
        {
            userCost.finish(this.evaluateStatue, "")
        }
    }

    /*
    * 评估失败
     */

    def evaluteFailure()
    {
        def userCost = UserCost.findBySourceIdAndSourceClass(this.id, this.class.toString())
        if (userCost)
        {
            userCost.finish(this.evaluateStatue, this.failReason)
        }
    }

    // 更新匹配记录数量
    def updateMatchNum()
    {
        this.batch.updateBatchCount()
    }

    def beforeUpdate()
    {
        modifiedDate = new Date()
    }
}
